package training.project.app.web;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import training.project.app.domain.UserAccount;
import training.project.app.security.ApplicationUserDetails;
import training.project.app.service.UserService;

@Controller
@RequestMapping("/profile")
public class ProfileController
	{
		@Autowired
		private UserService userService;
		
		@PreAuthorize("isFullyAuthenticated() and hasAnyRole('ROLE_ADMIN','ROLE_USER')")	
		@RequestMapping(value = { "", "/" }, method = RequestMethod.GET)
		public String showUserProfile(
				Authentication authentication,
				HttpSession session, Model model) {

			ApplicationUserDetails appUser = (ApplicationUserDetails) authentication.getPrincipal();
			
		    
			UserAccount user = appUser.getAccount();
			session.setAttribute("user", user);
			
			return "profile";
		}
		
		@PreAuthorize("isFullyAuthenticated()")	
		@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
		public ModelAndView showUserProfileByID(
				Authentication authentication,
				@PathVariable String userId,
				@PathVariable("userId") UserAccount userModelTest,
				HttpSession session, Model model) {

		    
		    
			ModelAndView mav = new ModelAndView();
			mav.setViewName("profile");
			mav.addObject("userModelTest", userModelTest);
			Object userObject = session.getAttribute("user");
			if ((userObject != null) && (userObject instanceof UserAccount)) {
				UserAccount user = (UserAccount) userObject;
				
				mav.addObject("user", user);
			}
			
			return mav;
		}
	}
